/**
 * Controller for UniverseMap
 * @author Team Love is Like Sand
 * @version 1.0
 *
 */

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * Map Controller
 * @author kushagramansingh
 * @version 1.0
 */
public class UniverseMapController {
	
	/**
	 * Player in game
	 */
	private Player player;
	
	/**
	 * Constructor for UniverseMapController
	 * @param player of game
	 */
	public UniverseMapController(Player player){
		this.player = player;
	}
	
	/**
	 * Sets the system and deals with MarketController and Window
	 * @param system clicked
	 * @param frame clicked in
	 */
	public void systemAction(SolarSystem system, JFrame frame){
		frame.setVisible(false);
		int distance = (int) system.getPoint().distance(player.getSystem().getPoint());
		player.setFuel(distance);
		MarketController controller = new MarketController(
				player, system.getTrader(), frame);
		
		if(!system.equals(player.getSystem())){
			Encounter encounter = new Encounter(player, new JFrame(), controller);
		}
		player.setSystem(system);
		
	}
	
	/**
	 * Lets the systems that are reachable to be clicked on 
	 * and the others to not be clicked on
	 * @param button clicked
	 * @param system represented
	 */
	public void reachable(JButton button, SolarSystem system){
		if(player.getSystem().equals(system)){
			button.setIcon(new ImageIcon("Images/ufo.png"));
		}
		else{
			button.setIcon(new ImageIcon("Images/solarIcon.jpg"));
		}
		if(player.getSystem().getPoint().distance(system.getPoint()) < player.getFuel()){
			button.setEnabled(true);
		}
		else{
			button.setEnabled(false);
		}
	}
	
	/**
	 * Saves Universe in a file for future use
	 * @param uni saved
	 */
	public void save(Universe uni){
		FileOutputStream fileOut = null;
		ObjectOutputStream out = null;
		try{
			File f = new File("save.ser");
			fileOut = new FileOutputStream(f);
			out = new ObjectOutputStream(fileOut);
			out.writeObject(player);
			out.writeObject(uni);
			JOptionPane.showMessageDialog(new JFrame(), "Game Saved");
		}
		catch(IOException e){
			e.printStackTrace();
		}
		finally{
			try{
				fileOut.close();
				out.close();
			}
			catch(IOException e){
				e.getStackTrace();
			}
		}
	}
}
